﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Collections.ObjectModel;

namespace DataGridTest
{

    static class  SQLHelper
    {
        private static string connStr = "Data source=.;Initial Catalog=sksf;User ID=SA;PassWord=;Integrated Security=false";


        //封装查询sql语句,这个要看你是否需要用存储过程
        public static SqlDataReader GetSqlDataReader(string sql)
        {
            //我要吃饭了，晚点来写哈
            SqlConnection conn = new SqlConnection(connStr);
            SqlCommand cmd = new SqlCommand(sql, conn);
            try
            {
                conn.Open();
                return cmd.ExecuteReader(CommandBehavior.CloseConnection);
            }
            catch (Exception ex)
            {
                conn.Close();
                //这里可以写日志，等等
                throw ex;
            }

        }
    }

    class kqj:ICloneable
    {
        public int id { get; set; }
        public int card_no { get; set; }
        public string ygh { get; set; }
        public string name { get; set; }

        public object Clone()//克隆，这样可以ti gao xiao lv
        {
            return MemberwiseClone();
        }
    }

    class kqjService
    {
        public List<kqj> GetALLKqj()
        {
            string sql = "select id,card_no,ygh,name from kqj";
            SqlDataReader reader = SQLHelper.GetSqlDataReader(sql);
            List<kqj> result = new List<kqj>();
            kqj p = new kqj();
            while (reader.Read())
            {
                //这里其实可以封装成泛型通用的，这里不做介绍
                //下面还要判断isnull
                kqj obj = p.Clone() as kqj;
                obj.id = reader["id"] is DBNull ?0: Convert.ToInt32(reader["id"]);//这样才是标准的
                obj.card_no = Convert.ToInt32(reader["card_no"]);
                obj.name = reader["name"].ToString();
                obj.ygh = reader["ygh"].ToString();
                result.Add(obj);
            }

            reader.Close();
            return result;


        }
    }


    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {

        //连接字符串

        //首先要考虑分层，

        public MainWindow()
        {
            InitializeComponent();

            //dgList.ItemsSource = GetDataSource().DefaultView;
            init();
        }

        private void init()
        {
            //dgList.ItemsSource = new kqjService().GetALLKqj();//理论上这样没问题，但是不能这样

            data = new ObservableCollection<kqj>(new kqjService().GetALLKqj());//这样是同步的，比如动态添加。，删除数据
            dgList.ItemsSource = data;
        }
        private ObservableCollection<kqj> data = null;

        /// <summary>
        /// 得到数据源
        /// </summary>
        /// <returns></returns>
        private DataTable GetDataSource()
        {
            DataTable dt = new DataTable("Source");

            //新建一列
            DataColumn dcTypeName = new DataColumn();
            //指定列名
            dcTypeName.ColumnName = "Name";
            //添加
            dt.Columns.Add(dcTypeName);

            DataColumn dcNo = new DataColumn();
            dcNo.ColumnName = "No";
            dt.Columns.Add(dcNo);

            DataColumn dcUser = new DataColumn();
            dcUser.ColumnName = "IsUse";
            dt.Columns.Add(dcUser);

            foreach (var item in Data.list)
            {
                DataRow row = dt.NewRow();
                row["Name"] = item.Name;
                row["No"] = item.No;
                row["IsUse"] = item.IsUse;
                dt.Rows.Add(row);
            }

            return dt;
        }

        /// <summary>
        /// DataGrid的右键菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgList_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (dgList.SelectedIndex > -1)
            {
                //ContextMenu contextMenu = new ContextMenu();

                //MenuItem menuItemEdit = new MenuItem();
                //menuItemEdit.Header = "得到本行数据";
                //menuItemEdit.Click += new RoutedEventHandler(MenuItemEdit_Click);
                //contextMenu.Items.Add(menuItemEdit);

                //dgList.ContextMenu = contextMenu;

                if (dgList.SelectedItems.Count > 0)
                {
                    int i = dgList.SelectedIndex;

                    DataRowView drv = dgList.Items[i] as DataRowView;

                    MessageBox.Show("本行数据：" + drv.Row.Table.Rows[i]["Name"].ToString() + ":" + GetTextBoxValue(i, 1) + ":" + GetCheckBoxValue(i, 2));
                }
                else
                {
                    MessageBox.Show("请先选中一条数据!");
                }
            }
        }

        /// <summary>
        /// 右键菜单Item事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuItemEdit_Click(object sender, RoutedEventArgs e)
        {
            if (dgList.SelectedItems.Count > 0)
            {
                int i = dgList.SelectedIndex;

                DataRowView drv = dgList.Items[i] as DataRowView;

                MessageBox.Show("本行数据：" + drv.Row.Table.Rows[i]["Name"].ToString() + ":" + GetTextBoxValue(i, 1) + ":" + GetCheckBoxValue(i, 2));
            }
            else
            {
                MessageBox.Show("请先选中一条数据!");
            }
        }

        #region 方法

        public static T GetVisualChild<T>(Visual parent) where T : Visual
        {
            T childContent = default(T);
            int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < numVisuals; i++)
            {
                Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
                childContent = v as T;
                if (childContent == null)
                {
                    childContent = GetVisualChild<T>(v);
                }
                if (childContent != null)
                {
                    break;
                }
            }
            return childContent;
        }

        /// <summary>
        /// 得到DataGrid的一个单元格
        /// </summary>
        /// <param name="rowIndex">行索引</param>
        /// <param name="cellIndex">列索引</param>
        /// <returns></returns>
        private DataGridCell GetDataGridCell(int rowIndex, int cellIndex)
        {
            DataGridRow row = (DataGridRow)dgList.ItemContainerGenerator.ContainerFromIndex(rowIndex);
            dgList.UpdateLayout();
            row = (DataGridRow)dgList.ItemContainerGenerator.ContainerFromIndex(rowIndex);
            DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);
            DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(cellIndex);
            dgList.ScrollIntoView(row, dgList.Columns[cellIndex]);
            cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(cellIndex);

            return cell;
        }

        /// <summary>
        /// 得到TextBox里的值
        /// </summary>
        /// <param name="rowIndex">行索引</param>
        /// <param name="cellIndex">列索引</param>
        /// <returns>TextBox里的值</returns>
        private string GetTextBoxValue(int rowIndex, int cellIndex)
        {
            var obj = VisualTreeHelper.GetChild((ContentPresenter)GetDataGridCell(rowIndex, cellIndex).Content, 0);
            TextBox tbox = null;
            if (obj != null && obj.DependencyObjectType.Name == "TextBox")
            {
                tbox = (TextBox)obj;
            }
            return tbox.Text;
        }

        /// <summary>
        /// 得到CheckBox里的值
        /// </summary>
        /// <param name="rowIndex">行索引</param>
        /// <param name="cellIndex">列索引</param>
        /// <returns>CheckBox里的值</returns>
        private string GetCheckBoxValue(int rowIndex, int cellIndex)
        {
            var obj = VisualTreeHelper.GetChild((ContentPresenter)GetDataGridCell(rowIndex, cellIndex).Content, 0);
            CheckBox chk = null;
            if (obj != null && obj.DependencyObjectType.Name == "CheckBox")
            {
                chk = (CheckBox)obj;
            }
            return chk.IsChecked.ToString();
        }

        #endregion
    }

    public class Data
    {
        public string Name { set; get; }
        public int No { set; get; }
        public bool IsUse { set; get; }

        public Data(string name, int no, bool isuse)
        {
            Name = name;
            No = no;
            IsUse = isuse;
        }

        public static List<Data> list = new List<Data>()
        {
            new Data("陕西",1,true),
            new Data("西安",2,true),
            new Data("汉中",3,true),
            new Data("宝鸡",4,false),
            new Data("咸阳",5,false),
            new Data("渭南",6,false),
            new Data("安康",7,true),
            new Data("榆林",8,false),
            new Data("延安",9,true)
        };
    }

}
